from django import newforms as forms
from models import *


__all__ = ('NewDocumentForm', 'ChangeDocumentForm','NewVersionForm', 
           'CategoryForm', 'AccessDocumentForm')

class NewDocumentForm(forms.Form):
    category = forms.ModelChoiceField(queryset=Category.objects.all())
    file = forms.FileField()
    filename = forms.CharField(max_length=128)
    version = forms.CharField(max_length=10, initial="1")
    author = forms.CharField(max_length=128, required=False)
    beneficient = forms.CharField(max_length=128, required=False)
    issued_on = forms.DateTimeField(required=False)
    description = forms.CharField(widget=forms.Textarea(), required=False)
    public = forms.BooleanField()
    access_code = forms.CharField(max_length=48, required=False)
    
    def clean_filename(self):
        value = self.cleaned_data.get('filename')
        if value and Document.objects.filter(filename=value).count() > 0:
            raise forms.ValidationError("This file name already exist.")
        return value
    

class ChangeDocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        exclude = ('owner', 'filename')


class NewVersionForm(forms.Form):
    version = forms.CharField(max_length=10)
    file = forms.FileField()
    
    def __init__(self, data=None, files=None, document=None, *args, **kwargs):
        super(NewVersionForm, self).__init__(data, files, *args, **kwargs)
        self.document = document
    
    def clean_version(self):
        ver = self.cleaned_data.get('version')
        if ver and DocumentVersion.objects.filter(
                            version=ver, document=self.document).count() > 0:
            raise forms.ValidationError("This version already defined for document.")
        return ver


class CategoryForm(forms.ModelForm):
    class Meta:
        model = Category


class AccessDocumentForm(forms.Form):
    code = forms.CharField(max_length=42)
    
    def __init__(self, data=None, document=None, *args, **kwargs):
        super(AccessDocumentForm, self).__init__(data, *args, **kwargs)
        self.document = document
    
    def clean_code(self):
        code = self.cleaned_data.get('code')
        if not code: return code
        if self.document.access_code != code:
            raise forms.ValidationError("Invalid access code")